<template>
  <div class="menus-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>菜单管理</h2>
      <p>管理系统菜单，包括菜单的增删改查和状态管理</p>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="search-bar">
      <div class="search-form">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入菜单名称"
          style="width: 200px; margin-right: 10px;"
          clearable
        />
        <el-select
          v-model="searchForm.status"
          placeholder="菜单状态"
          style="width: 120px; margin-right: 10px;"
          clearable
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-select
          v-model="searchForm.type"
          placeholder="菜单类型"
          style="width: 120px; margin-right: 10px;"
          clearable
        >
          <el-option label="目录" :value="1" />
          <el-option label="菜单" :value="2" />
          <el-option label="按钮" :value="3" />
        </el-select>
        <el-button type="primary" @click="getMenuList">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">新增菜单</el-button>
      </div>
    </div>

    <!-- 菜单树形表格 -->
    <div class="table-container">
      <el-table
        :data="menuTreeData"
        style="width: 100%"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        v-loading="loading"
        border
      >
        <el-table-column prop="name" label="菜单名称" min-width="200">
          <template #default="scope">
            <div class="menu-name-cell" :class="`menu-level-${getMenuLevel(scope.row)}`">
              <div class="menu-icon-wrapper">
                <i :class="scope.row.icon || getDefaultIcon(scope.row.type)" class="menu-icon"></i>
              </div>
              <span class="menu-name">{{ scope.row.name }}</span>
              <el-tag 
                v-if="scope.row.type === 1" 
                type="info" 
                size="small" 
                class="menu-type-badge"
              >目录</el-tag>
              <el-tag 
                v-else-if="scope.row.type === 3" 
                type="warning" 
                size="small" 
                class="menu-type-badge"
              >按钮</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="菜单路径" min-width="180">
          <template #default="scope">
            <span v-if="scope.row.path">{{ scope.row.path }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 1" type="info" size="small">目录</el-tag>
            <el-tag v-else-if="scope.row.type === 2" type="primary" size="small">菜单</el-tag>
            <el-tag v-else-if="scope.row.type === 3" type="warning" size="small">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleToggleStatus(scope.row)"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="permission" label="权限标识" min-width="150">
          <template #default="scope">
            <span v-if="scope.row.permission">{{ scope.row.permission }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleAddChild(scope.row)" v-if="scope.row.type !== 3">新增子菜单</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 菜单表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuFormRules"
        label-width="100px"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio :label="1">目录</el-radio>
            <el-radio :label="2">菜单</el-radio>
            <el-radio :label="3">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="parentMenuOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择父级菜单"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path" v-if="menuForm.type === 2">
          <el-input v-model="menuForm.path" placeholder="请输入菜单路径" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-input v-model="menuForm.icon" placeholder="请输入图标类名" />
        </el-form-item>
        <el-form-item label="权限标识" prop="permission">
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="menuForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as menuApi from '@/api/menu'

// 响应式数据
const loading = ref(false)
const menuList = ref([])
const menuTreeData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const parentMenuOptions = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  status: null,
  type: null
})

// 菜单表单
const menuForm = reactive({
  id: null,
  name: '',
  path: '',
  icon: '',
  parentId: null,
  sort: 0,
  type: 1,
  status: 1,
  permission: ''
})

// 表单引用
const menuFormRef = ref()

// 表单验证规则
const menuFormRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ]
}

/**
 * 获取菜单列表
 */
const getMenuList = async () => {
  loading.value = true
  try {
    // 获取菜单树形数据
    const response = await menuApi.getMenuTree()
    if (response.code === 200) {
      menuList.value = flattenMenuTree(response.data)
      menuTreeData.value = response.data
      // 如果有搜索条件，进行过滤
      if (searchForm.name || searchForm.status !== null || searchForm.type !== null) {
        menuTreeData.value = filterMenuTree(response.data)
      }
    } else {
      ElMessage.error(response.message || '获取菜单列表失败')
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    ElMessage.error('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 将树形菜单数据扁平化
 */
const flattenMenuTree = (tree) => {
  const result = []
  const flatten = (nodes) => {
    nodes.forEach(node => {
      result.push(node)
      if (node.children && node.children.length > 0) {
        flatten(node.children)
      }
    })
  }
  flatten(tree)
  return result
}

/**
 * 获取父级菜单选项
 */
const getParentMenuOptions = async () => {
  try {
    const response = await menuApi.getEnabledMenus()
    if (response.code === 200) {
      // 添加根节点选项
      parentMenuOptions.value = [
        { id: 0, name: '根目录', children: [] },
        ...buildMenuTree(response.data)
      ]
    }
  } catch (error) {
    console.error('获取父级菜单选项失败:', error)
  }
}

/**
 * 构建菜单树
 */
const buildMenuTree = (menus) => {
  const tree = []
  const map = {}
  
  // 创建映射
  menus.forEach(menu => {
    map[menu.id] = { ...menu, children: [] }
  })
  
  // 构建树结构
  menus.forEach(menu => {
    if (menu.parentId === 0 || menu.parentId === null) {
      tree.push(map[menu.id])
    } else if (map[menu.parentId]) {
      map[menu.parentId].children.push(map[menu.id])
    }
  })
  
  // 按排序字段排序
  const sortTree = (nodes) => {
    nodes.sort((a, b) => (a.sort || 0) - (b.sort || 0))
    nodes.forEach(node => {
      if (node.children && node.children.length > 0) {
        sortTree(node.children)
      }
    })
  }
  
  sortTree(tree)
  return tree
}

/**
 * 过滤菜单树
 */
const filterMenuTree = (tree) => {
  const filterNode = (node) => {
    // 检查当前节点是否匹配搜索条件
    let matches = true
    
    if (searchForm.name && !node.name.includes(searchForm.name)) {
      matches = false
    }
    
    if (searchForm.status !== null && node.status !== searchForm.status) {
      matches = false
    }
    
    if (searchForm.type !== null && node.type !== searchForm.type) {
      matches = false
    }
    
    // 递归过滤子节点
    let filteredChildren = []
    if (node.children && node.children.length > 0) {
      filteredChildren = node.children.map(filterNode).filter(child => child !== null)
    }
    
    // 如果当前节点匹配或有匹配的子节点，则保留
    if (matches || filteredChildren.length > 0) {
      return {
        ...node,
        children: filteredChildren
      }
    }
    
    return null
  }
  
  return tree.map(filterNode).filter(node => node !== null)
}

/**
 * 重置搜索
 */
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = null
  searchForm.type = null
  getMenuList()
}

/**
 * 处理新增
 */
const handleAdd = () => {
  dialogTitle.value = '新增菜单'
  isEdit.value = false
  dialogVisible.value = true
  getParentMenuOptions()
}

/**
 * 处理新增子菜单
 */
const handleAddChild = (row) => {
  dialogTitle.value = '新增子菜单'
  isEdit.value = false
  menuForm.parentId = row.id
  dialogVisible.value = true
  getParentMenuOptions()
}

/**
 * 处理编辑
 */
const handleEdit = (row) => {
  dialogTitle.value = '编辑菜单'
  isEdit.value = true
  Object.assign(menuForm, row)
  dialogVisible.value = true
  getParentMenuOptions()
}

/**
 * 处理删除
 */
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await menuApi.deleteMenu(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getMenuList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 处理状态切换
 */
const handleToggleStatus = async (row) => {
  try {
    const response = await menuApi.toggleMenuStatus(row.id, row.status)
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
    } else {
      ElMessage.error(response.message || '状态更新失败')
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    console.error('切换菜单状态失败:', error)
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

/**
 * 处理表单提交
 */
const handleSubmit = async () => {
  try {
    await menuFormRef.value.validate()
    
    const response = isEdit.value
      ? await menuApi.updateMenu(menuForm.id, menuForm)
      : await menuApi.createMenu(menuForm)
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      getMenuList()
    } else {
      ElMessage.error(response.message || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交菜单表单失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  Object.assign(menuForm, {
    id: null,
    name: '',
    path: '',
    icon: '',
    parentId: null,
    sort: 0,
    type: 1,
    status: 1,
    permission: ''
  })
  menuFormRef.value?.clearValidate()
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

/**
 * 获取菜单层级
 */
const getMenuLevel = (menu) => {
  let level = 0
  let current = menu
  while (current && current.parentId) {
    level++
    current = menuList.value.find(m => m.id === current.parentId)
  }
  return level
}

/**
 * 获取默认图标
 */
const getDefaultIcon = (type) => {
  switch (type) {
    case 1: return 'el-icon-folder'
    case 2: return 'el-icon-document'
    case 3: return 'el-icon-setting'
    default: return 'el-icon-menu'
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getMenuList()
})
</script>

<style scoped>
.menus-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: white;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e4e7ed;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e4e7ed;
}

/* 树形表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table__header) {
  background: #fafbfc;
}

:deep(.el-table__header th) {
  background: #fafbfc !important;
  color: #606266;
  font-weight: 600;
  border-bottom: 2px solid #e4e7ed;
  padding: 16px 0;
}

:deep(.el-table__body tr) {
  transition: all 0.3s ease;
}

:deep(.el-table__body tr:hover) {
  background-color: #f8f9ff !important;
}

/* 树形结构缩进优化 */
:deep(.el-table__indent) {
  padding-left: 20px;
}

:deep(.el-table__expand-icon) {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  background: #f0f2f5;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

:deep(.el-table__expand-icon:hover) {
  background: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

:deep(.el-table__expand-icon--expanded) {
  background: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

/* 树形层级视觉效果 */
:deep(.el-table__row--level-1) {
  background: #fafbfc;
}

:deep(.el-table__row--level-2) {
  background: #f5f7fa;
}

:deep(.el-table__row--level-3) {
  background: #f0f2f5;
}

/* 菜单名称单元格样式 */
.menu-name-cell {
  display: flex;
  align-items: center;
  padding: 8px 0;
  gap: 8px;
  position: relative;
}

.menu-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 6px;
  background: rgba(64, 158, 255, 0.1);
  transition: all 0.3s ease;
}

.menu-icon {
  font-size: 14px;
  color: #409EFF;
  transition: all 0.3s ease;
}

.menu-name {
  font-weight: 500;
  color: #303133;
  flex: 1;
  transition: all 0.3s ease;
}

.menu-type-badge {
  margin-left: auto;
  font-size: 10px;
  padding: 0 6px;
  height: 18px;
  line-height: 16px;
  border-radius: 9px;
}

/* 不同层级的菜单样式 */
.menu-level-0 .menu-icon-wrapper {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.menu-level-0 .menu-icon {
  color: white;
  font-size: 16px;
}

.menu-level-0 .menu-name {
  font-weight: 600;
  font-size: 15px;
  color: #303133;
}

.menu-level-1 .menu-icon-wrapper {
  background: rgba(103, 194, 58, 0.15);
  border: 1px solid rgba(103, 194, 58, 0.3);
}

.menu-level-1 .menu-icon {
  color: #67c23a;
}

.menu-level-1 .menu-name {
  color: #606266;
}

.menu-level-2 .menu-icon-wrapper {
  background: rgba(230, 162, 60, 0.15);
  border: 1px solid rgba(230, 162, 60, 0.3);
}

.menu-level-2 .menu-icon {
  color: #e6a23c;
}

.menu-level-2 .menu-name {
  color: #909399;
  font-size: 14px;
}

/* 悬停效果 */
:deep(.el-table__body tr:hover) .menu-icon-wrapper {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

:deep(.el-table__body tr:hover) .menu-name {
  color: #409eff;
}

/* 类型标签样式优化 */
:deep(.el-tag) {
  border-radius: 12px;
  font-weight: 500;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

:deep(.el-tag--info) {
  background: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

:deep(.el-tag--primary) {
  background: #ecf5ff;
  border-color: #b3d8ff;
  color: #409eff;
}

:deep(.el-tag--warning) {
  background: #fdf6ec;
  border-color: #f5dab1;
  color: #e6a23c;
}

/* 状态开关样式 */
:deep(.el-switch) {
  --el-switch-on-color: #67c23a;
  --el-switch-off-color: #dcdfe6;
}

/* 操作按钮样式优化 */
:deep(.el-button--small) {
  padding: 5px 12px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff, #3a8ee6);
  border: none;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a, #5daf34);
  border: none;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c, #f25c5c);
  border: none;
}

.text-muted {
  color: #c0c4cc;
  font-style: italic;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 18px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

.dialog-footer {
  text-align: right;
  padding: 16px 24px;
  background: #fafbfc;
  border-radius: 0 0 12px 12px;
  margin: 0 -24px -24px -24px;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 树选择器样式 */
:deep(.el-tree-select) {
  border-radius: 6px;
}

/* 数字输入框样式 */
:deep(.el-input-number) {
  border-radius: 6px;
}

/* 单选按钮组样式 */
:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.el-radio) {
  margin-right: 0;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background: #409eff;
  border-color: #409eff;
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .menus-container {
    padding: 12px;
  }
  
  .search-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-form {
    flex-wrap: wrap;
    gap: 12px;
  }
  
  :deep(.el-table__body .cell) {
    padding: 8px 4px;
  }
}
</style>